#include <linux/clk.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/regulator/consumer.h>
#include <linux/sysfs.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/rk-camera-module.h>
#include <media/media-entity.h>
#include <media/v4l2-async.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-subdev.h>
#include <linux/pinctrl/consumer.h>
#include <linux/rk-preisp.h>

#define DRIVER_VERSION			KERNEL_VERSION(0, 0x0, 0x01)
//#define PIX_FORMAT			MEDIA_BUS_FMT_UYVY8_1X16
#define PIX_FORMAT				MEDIA_BUS_FMT_UYVY8_2X8
#define IRAYTEK_NAME			"iraytek"

struct regval {
	u16 addr;
	u8 val;
};

struct iraytek_mode {
	u32 bus_fmt;
	u32 width;
	u32 height;
	struct v4l2_fract max_fps;
	u32 hts_def;
	u32 vts_def;
	u32 exp_def;
	const struct regval *reg_list;
};

struct iraytek {
	struct i2c_client	*client;
	struct clk		*xvclk;
	struct gpio_desc	*reset_gpio;
	struct gpio_desc	*pwdn_gpio;

	struct v4l2_subdev	subdev;
	struct media_pad	pad;
	struct v4l2_ctrl_handler ctrl_handler;
	struct v4l2_ctrl	*exposure;
	struct v4l2_ctrl	*anal_gain;
	struct v4l2_ctrl	*digi_gain;
	struct v4l2_ctrl	*hblank;
	struct v4l2_ctrl	*vblank;
	struct v4l2_ctrl	*test_pattern;
	struct mutex		mutex;
	bool			streaming;
	bool			power_on;
	const struct iraytek_mode *cur_mode;
	u32			module_index;
	const char		*module_facing;
	const char		*module_name;
	const char		*len_name;
};

#define to_iraytek(sd) container_of(sd, struct iraytek, subdev)

static const struct iraytek_mode supported_modes[] = {
	{
		.bus_fmt = PIX_FORMAT,
		.width = 640,
		.height = 512,
		.max_fps = {
			.numerator = 10000,
			.denominator = 500000,
		},
		.exp_def = 0x0100,
		.hts_def = 0x044c * 2,
		.vts_def = 0x0465,
	}
};

static int __iraytek_start_stream(struct iraytek *iraytek)
{
	printk(KERN_ERR "%s enter\n", __func__);
	return 0;
}

static int __iraytek_stop_stream(struct iraytek *iraytek)
{
	printk(KERN_ERR "%s enter\n", __func__);
	return 0;
}

static int iraytek_s_stream(struct v4l2_subdev *sd, int on)
{
	struct iraytek *iraytek = to_iraytek(sd);
	struct i2c_client *client = iraytek->client;
	int ret = 0;

	mutex_lock(&iraytek->mutex);
	printk(KERN_CRIT "on = %d, iraytek->streaming = %d\n", on, iraytek->streaming);
	on = !!on;
	if (on == iraytek->streaming)
		goto unlock_and_return;

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}

		ret = __iraytek_start_stream(iraytek);
		if (ret) {
			v4l2_err(sd, "start stream failed while write regs\n");
			pm_runtime_put(&client->dev);
			goto unlock_and_return;
		}
	} else {
		__iraytek_stop_stream(iraytek);
		pm_runtime_put(&client->dev);
	}

	iraytek->streaming = on;
unlock_and_return:
	mutex_unlock(&iraytek->mutex);

	return ret;
}


#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static int iraytek_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
	struct iraytek *iraytek = to_iraytek(sd);
	struct v4l2_mbus_framefmt *try_fmt =
				v4l2_subdev_get_try_format(sd, fh->pad, 0);
	const struct iraytek_mode *def_mode = &supported_modes[0];

	mutex_lock(&iraytek->mutex);
	/* Initialize try_fmt */
	try_fmt->width = def_mode->width;
	try_fmt->height = def_mode->height;
	try_fmt->code = PIX_FORMAT;
	try_fmt->field = V4L2_FIELD_NONE;		//V4L2_FIELD_NONE	V4L2_FIELD_INTERLACED
	mutex_unlock(&iraytek->mutex);
	/* No crop or compose */

	return 0;
}
#endif


static int iraytek_g_frame_interval(struct v4l2_subdev *sd,
				   struct v4l2_subdev_frame_interval *fi)
{
	struct iraytek *iraytek = to_iraytek(sd);
	const struct iraytek_mode *mode = iraytek->cur_mode;

	mutex_lock(&iraytek->mutex);
	fi->interval = mode->max_fps;
	mutex_unlock(&iraytek->mutex);

	return 0;
}

static int iraytek_querystd(struct v4l2_subdev *sd, v4l2_std_id *std)
{

	printk(KERN_CRIT "%s\n", __func__);
	//*std = V4L2_STD_ATSC;
	*std = V4L2_STD_ATSC;
	return 0;
}


static int iraytek_enum_frame_interval(struct v4l2_subdev *sd,
				       struct v4l2_subdev_pad_config *cfg,
				       struct v4l2_subdev_frame_interval_enum *fie)
{
	if (fie->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	//if (fie->code != PIX_FORMAT)
	//	return -EINVAL;

	fie->code = supported_modes[fie->index].bus_fmt;
	fie->width = supported_modes[fie->index].width;
	fie->height = supported_modes[fie->index].height;
	fie->interval = supported_modes[fie->index].max_fps;
	fie->reserved[0] = 0;
	return 0;
}

static int iraytek_enum_mbus_code(struct v4l2_subdev *sd,
				 struct v4l2_subdev_pad_config *cfg,
				 struct v4l2_subdev_mbus_code_enum *code)
{
	printk(KERN_CRIT "[zoro] %s\n", __func__);
	if (code->index != 0)
		return -EINVAL;
	code->code = PIX_FORMAT;

	return 0;
}

static int iraytek_enum_frame_sizes(struct v4l2_subdev *sd,
				   struct v4l2_subdev_pad_config *cfg,
				   struct v4l2_subdev_frame_size_enum *fse)
{
	if (fse->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	if (fse->code != PIX_FORMAT)
		return -EINVAL;

	fse->min_width  = supported_modes[fse->index].width;
	fse->max_width  = supported_modes[fse->index].width;
	fse->max_height = supported_modes[fse->index].height;
	fse->min_height = supported_modes[fse->index].height;

	return 0;
}

static int iraytek_set_fmt(struct v4l2_subdev *sd,
			  struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *fmt)
{
	struct iraytek *iraytek = to_iraytek(sd);
	const struct iraytek_mode *mode;

	mutex_lock(&iraytek->mutex);

	mode = iraytek->cur_mode;
	fmt->format.code = PIX_FORMAT;
	fmt->format.width = mode->width;
	fmt->format.height = mode->height;
	fmt->format.field = V4L2_FIELD_NONE;		//V4L2_FIELD_NONE	V4L2_FIELD_INTERLACED
	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
		*v4l2_subdev_get_try_format(sd, cfg, fmt->pad) = fmt->format;
#else
		mutex_unlock(&iraytek->mutex);
		return -ENOTTY;
#endif
	} else {
		iraytek->cur_mode = mode;
	}

	mutex_unlock(&iraytek->mutex);

	return 0;
}

static int iraytek_get_selection(struct v4l2_subdev *sd,
		struct v4l2_subdev_pad_config *cfg,
		struct v4l2_subdev_selection *scl)
{
	struct iraytek *iraytek = to_iraytek(sd);
	const struct iraytek_mode *mode;

	mode = iraytek->cur_mode;

	switch(scl->target)
	{
		case V4L2_SEL_TGT_CROP_BOUNDS:
			scl->r.left = 0;
			scl->r.top = 0;
			scl->r.width = mode->width;
			scl->r.height = mode->height;
		break;
		default:
			printk(KERN_CRIT "[zoro] default ................\n");
		break;
	}
	return 0;
}

static int iraytek_get_fmt(struct v4l2_subdev *sd,
			  struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *fmt)
{
	struct iraytek *iraytek = to_iraytek(sd);
	const struct iraytek_mode *mode = iraytek->cur_mode;

	mutex_lock(&iraytek->mutex);
	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
		fmt->format = *v4l2_subdev_get_try_format(sd, cfg, fmt->pad);
#else
		mutex_unlock(&iraytek->mutex);
		return -ENOTTY;
#endif
	} else {
		fmt->format.width = mode->width;
		fmt->format.height = mode->height;
		fmt->format.code = PIX_FORMAT;
		fmt->format.field = V4L2_FIELD_NONE;		//V4L2_FIELD_NONE	V4L2_FIELD_INTERLACED
	}
	mutex_unlock(&iraytek->mutex);

	return 0;
}

static int iraytek_s_power(struct v4l2_subdev *sd, int on)
{
	struct iraytek *iraytek = to_iraytek(sd);
	struct i2c_client *client = iraytek->client;
	int ret = 0;

	mutex_lock(&iraytek->mutex);

	/* If the power state is not modified - no work to do. */
	if (iraytek->power_on == !!on)
		goto unlock_and_return;

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}

		iraytek->power_on = true;
	} else {
		pm_runtime_put(&client->dev);
		iraytek->power_on = false;
	}

unlock_and_return:
	mutex_unlock(&iraytek->mutex);

	return ret;
}

static int __iraytek_power_on(struct iraytek *iraytek)
{
	return 0;
}

static void __iraytek_power_off(struct iraytek *iraytek)
{
	return;
}

static int iraytek_runtime_resume(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct iraytek *iraytek = to_iraytek(sd);

	return __iraytek_power_on(iraytek);
}

static int iraytek_runtime_suspend(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct iraytek *iraytek = to_iraytek(sd);

	__iraytek_power_off(iraytek);

	return 0;
}


static const struct dev_pm_ops iraytek_pm_ops = {
	SET_RUNTIME_PM_OPS(iraytek_runtime_suspend,
			   iraytek_runtime_resume, NULL)
};

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static const struct v4l2_subdev_internal_ops iraytek_internal_ops = {
	.open = iraytek_open,
};
#endif

static void iraytek_get_module_inf(struct iraytek *iraytek,
				  struct rkmodule_inf *inf)
{
	memset(inf, 0, sizeof(*inf));
	strlcpy(inf->base.sensor, IRAYTEK_NAME, sizeof(inf->base.sensor));
	strlcpy(inf->base.module, iraytek->module_name,
		sizeof(inf->base.module));
	strlcpy(inf->base.lens, iraytek->len_name, sizeof(inf->base.lens));
}

static long iraytek_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
	struct iraytek *iraytek = container_of(sd, struct iraytek, subdev);
	long ret = 0;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		iraytek_get_module_inf(iraytek, (struct rkmodule_inf *)arg);
		break;
	case RKMODULE_SET_QUICK_STREAM:
		break;
	case RKMODULE_SET_HDR_CFG:
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}

#ifdef CONFIG_COMPAT
static long iraytek_compat_ioctl32(struct v4l2_subdev *sd,
				  unsigned int cmd, unsigned long arg)
{
	void __user *up = compat_ptr(arg);
	struct rkmodule_inf *inf;
	long ret;
	u32 stream = 0;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		inf = kzalloc(sizeof(*inf), GFP_KERNEL);
		if (!inf) {
			ret = -ENOMEM;
			return ret;
		}

		ret = iraytek_ioctl(sd, cmd, inf);
		if (!ret)
			ret = copy_to_user(up, inf, sizeof(*inf));
		kfree(inf);
		break;
	case RKMODULE_SET_QUICK_STREAM:
		ret = copy_from_user(&stream, up, sizeof(u32));
		if (!ret)
			ret = iraytek_ioctl(sd, cmd, &stream);
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}
#endif

static const struct v4l2_subdev_core_ops iraytek_core_ops = {
	.s_power = iraytek_s_power,
	.ioctl = iraytek_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl32 = iraytek_compat_ioctl32,
#endif
};
#if 1
static int iraytek_g_mbus_config(struct v4l2_subdev *sd, unsigned int pad_id,
				struct v4l2_mbus_config *config)
{
	printk(KERN_CRIT "%s\n", __func__);
	config->type = V4L2_MBUS_BT656;				//V4L2_MBUS_PARALLEL, V4L2_MBUS_BT656
	config->flags = RKMODULE_CAMERA_BT656_CHANNELS |
			V4L2_MBUS_HSYNC_ACTIVE_HIGH |
			V4L2_MBUS_VSYNC_ACTIVE_HIGH |
			V4L2_MBUS_PCLK_SAMPLE_RISING;
	return 0;
}
#endif
static const struct v4l2_subdev_video_ops iraytek_video_ops = {
	.s_stream = iraytek_s_stream,
	.g_frame_interval = iraytek_g_frame_interval,
	.querystd = iraytek_querystd,
};

static const struct v4l2_subdev_pad_ops iraytek_pad_ops = {
	.enum_mbus_code = iraytek_enum_mbus_code,
	.enum_frame_size = iraytek_enum_frame_sizes,
	.enum_frame_interval = iraytek_enum_frame_interval,
	.get_fmt = iraytek_get_fmt,
	.set_fmt = iraytek_set_fmt,
	.get_selection = iraytek_get_selection,
    .get_mbus_config = iraytek_g_mbus_config,

};

static const struct v4l2_subdev_ops iraytek_subdev_ops = {
	.core	= &iraytek_core_ops,
	.video	= &iraytek_video_ops,
	.pad	= &iraytek_pad_ops,
};



static int iraytek_initialize_controls(struct iraytek *iraytek)
{
	struct v4l2_ctrl_handler *handler;
	int ret;

	handler = &iraytek->ctrl_handler;
	ret = v4l2_ctrl_handler_init(handler, 9);
	if (ret)
		return ret;
	handler->lock = &iraytek->mutex;


	if (handler->error) {
		ret = handler->error;
		dev_err(&iraytek->client->dev,
			"Failed to init controls(%d)\n", ret);
		goto err_free_handler;
	}

	iraytek->subdev.ctrl_handler = handler;

	return 0;

err_free_handler:
	v4l2_ctrl_handler_free(handler);

	return ret;
}


static int iraytek_probe(struct i2c_client *client,
			const struct i2c_device_id *id)
{
	struct device *dev = &client->dev;
	struct iraytek *iraytek;
	struct v4l2_subdev *sd;
	char facing[2];
	int ret;


	printk("+++++++11111111111++++++iraytek_probe++++++++++++++++++++\n");

	printk(KERN_CRIT "[zoro] %s\n", __func__);
	dev_info(dev, "driver version: %02x.%02x.%02x",
		DRIVER_VERSION >> 16,
		(DRIVER_VERSION & 0xff00) >> 8,
		DRIVER_VERSION & 0x00ff);

	iraytek = devm_kzalloc(dev, sizeof(*iraytek), GFP_KERNEL);
	if (!iraytek)
		return -ENOMEM;

	iraytek->client = client;
	iraytek->cur_mode = &supported_modes[0];

	ret = of_property_read_u32(dev->of_node, RKMODULE_CAMERA_MODULE_INDEX,
				   &iraytek->module_index);
	ret |= of_property_read_string(dev->of_node, RKMODULE_CAMERA_MODULE_FACING,
				       &iraytek->module_facing);
	ret |= of_property_read_string(dev->of_node, RKMODULE_CAMERA_MODULE_NAME,
				       &iraytek->module_name);
	ret |= of_property_read_string(dev->of_node, RKMODULE_CAMERA_LENS_NAME,
				       &iraytek->len_name);
	if (ret) {
		dev_err(dev, "could not get module information!\n");
		return -EINVAL;
	}
	printk("+++++++2222222++++++iraytek_probe++++++++++++++++++++\n");
	iraytek->xvclk = devm_clk_get(dev, "xvclk");
	if (IS_ERR(iraytek->xvclk)) {
		dev_err(dev, "Failed to get xvclk\n");
		return -EINVAL;
	}
#if 0
	iraytek->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
	if (IS_ERR(iraytek->reset_gpio))
		dev_warn(dev, "Failed to get reset-gpios\n");
	iraytek->pwdn_gpio = devm_gpiod_get(dev, "pwdn", GPIOD_OUT_LOW);
	if (IS_ERR(iraytek->pwdn_gpio))
		dev_warn(dev, "Failed to get pwdn-gpios\n");
#endif
	mutex_init(&iraytek->mutex);

	sd = &iraytek->subdev;
	v4l2_i2c_subdev_init(sd, client, &iraytek_subdev_ops);

	ret = iraytek_initialize_controls(iraytek);
	if (ret)
		goto err_free_handler;

	ret = __iraytek_power_on(iraytek);
	if (ret)
		goto err_free_handler;
	printk("+++++++3333333++++++iraytek_probe++++++++++++++++++++\n");
#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
	sd->internal_ops = &iraytek_internal_ops;
	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE |
		     V4L2_SUBDEV_FL_HAS_EVENTS;
#endif

#if defined(CONFIG_MEDIA_CONTROLLER)
	iraytek->pad.flags = MEDIA_PAD_FL_SOURCE;
	sd->entity.function = MEDIA_ENT_F_CAM_SENSOR;
	ret = media_entity_pads_init(&sd->entity, 1, &iraytek->pad);
	if (ret < 0)
		goto err_power_off;
#endif

	memset(facing, 0, sizeof(facing));

	if (strcmp(iraytek->module_facing, "back") == 0)
		facing[0] = 'b';
	else
		facing[0] = 'f';

	if (!sd->dev)
		dev_err(dev, "sd dev is null\n");
	printk("+++++++444444++++++iraytek_probe++++++++++++++++++++\n");
	snprintf(sd->name, sizeof(sd->name), "m%02d_%s_%s %s",
		 iraytek->module_index, facing,
		 IRAYTEK_NAME, dev_name(sd->dev));

	ret = v4l2_async_register_subdev_sensor_common(sd);
	if (ret) {
		dev_err(dev, "v4l2 async register subdev failed\n");
		goto err_clean_entity;
	}

	pm_runtime_set_active(dev);
	pm_runtime_enable(dev);
	pm_runtime_idle(dev);
	printk("+++++++555555++++++iraytek_probe++++++++++++++++++++\n");
	dev_err(dev, "v4l2 async register subdev sucessfully\n");

	return 0;

err_clean_entity:
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
    	printk("+++++++666666++++++iraytek_probe++++++++++++++++++++\n");
err_power_off:
	__iraytek_power_off(iraytek);
err_free_handler:
	v4l2_ctrl_handler_free(&iraytek->ctrl_handler);


	mutex_destroy(&iraytek->mutex);

	return ret;
}

static int iraytek_remove(struct i2c_client *client)
{
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct iraytek *iraytek = to_iraytek(sd);

	v4l2_async_unregister_subdev(sd);
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
	v4l2_ctrl_handler_free(&iraytek->ctrl_handler);
	mutex_destroy(&iraytek->mutex);

	pm_runtime_disable(&client->dev);
	if (!pm_runtime_status_suspended(&client->dev))
		__iraytek_power_off(iraytek);
	pm_runtime_set_suspended(&client->dev);

	return 0;
}

#if IS_ENABLED(CONFIG_OF)
static const struct of_device_id iraytek_of_match[] = {
	{ .compatible = "lda640-v4l2" },
	{},
};
MODULE_DEVICE_TABLE(of, iraytek_of_match);
#endif

static const struct i2c_device_id iraytek_match_id[] = {
	{"lda640-v4l2", 0 },
	{},
};

static struct i2c_driver iraytek_i2c_driver = {
	.driver = {
		.name = IRAYTEK_NAME,
		.of_match_table = of_match_ptr(iraytek_of_match),
	},
	.probe		= &iraytek_probe,
	.remove	= &iraytek_remove,
	.id_table	= iraytek_match_id,
};

static int __init sensor_mod_init(void)
{
	printk("++++iraytek+bt656+++++sensor_mod_init++++++++++++++++++++\n");
	return i2c_add_driver(&iraytek_i2c_driver);
}
static void __exit sensor_mod_exit(void)
{

	i2c_del_driver(&iraytek_i2c_driver);
}

device_initcall_sync(sensor_mod_init);
module_exit(sensor_mod_exit);

MODULE_DESCRIPTION("Iraytek sensor driver");
MODULE_LICENSE("GPL v2");

